package fr.ssd.sdl.resolver;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import fr.ssd.sdl.parser.Parameter;
import fr.ssd.sdl.parser.Parser;
import fr.ssd.sdl.parser.ParserException;
import fr.ssd.sdl.utils.JdbcHelper;

public class KeyResolverImpl implements KeyResolver {

	/**
	 * <table.column, values>
	 */
	Set<Parameter> keys = new HashSet<Parameter>();
	Map<String, Integer> maxKeys = new HashMap<String, Integer>();

	Parser parser;

	public void setParser(Parser parser) {
		this.parser = parser;
	}

	/**
	 * ${foo.id.1}
	 * 
	 * @throws SQLException
	 */
	@Override
	public String resolve(String sqlStatement) throws ResolverException {
		try {
			parser.parseStatement(sqlStatement, keys);
			for (Parameter value : keys) {
				if (value.resolvedKey == null) {
					resolveNewKey(value);
				}
			}
			return parser.replaceKeys(sqlStatement, keys);
		} catch (ParserException e) {
			throw new ResolverException(e);
		} catch (SQLException e) {
			throw new ResolverException(e);
		}
	}

	//
	// private void printKeys() {
	// System.out.println("--- print keys ---");
	// for(Parameter value : keys){
	// System.out.println(value);
	// }
	// System.out.println("---  ---");
	// }

	private void resolveNewKey(Parameter value) throws SQLException {
		Integer i = maxKeys.get(value.table + "." + value.column);
		if (i == null) {
			Statement s = JdbcHelper.getInsertStatement();
			ResultSet rs = s.executeQuery("select max(" + value.column
					+ ") as max from " + value.table);
			rs.next();
			value.resolvedKey = String.valueOf(rs.getInt("max") + 1);
			i = new Integer(value.resolvedKey);
		} else {
			i++;
			value.resolvedKey = i.toString();
		}
		maxKeys.put(value.table + "." + value.column, i);
		// System.out.println("[resolveNewKey] "+value);
	}

}
